<script setup>

import {getToken} from "@/utils/auth.js";
import {genFileId} from "element-plus";

const {proxy} = getCurrentInstance()
const emits = defineEmits(['uploadFileSuccess'])
const uploadRef = ref()
const upload = reactive({
  open: false,
  isUploading: false,
  headers: {token: getToken()},
  url: '',
  title: "",
  accept: '',
  name: '',
  data: null
})

const props = defineProps({
  uploadParams: {
    type: Object
  }
})

onMounted(() => {
  Object.entries(props.uploadParams).forEach(([key, value]) => {
    upload[key] = value
  })
})

defineExpose({
  openUploadDialog
})

function closeDialog() {
  upload.open = false
}

function openUploadDialog() {
  upload.open = true
}

const handleExceed = (files) => {
  //清除并覆盖先前选择的文件
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value.handleStart(file)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  const code = response.code
  if ('200' !== code) {
    proxy.$modal.alertError('上传失败：' + response.message)
  } else {
    upload.open = false
    proxy.$modal.alertSuccess("上传成功")
    emits('uploadFileSuccess')
  }
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
}

/** 文件上传失败处理 */
const handleFileFail = () => {
  upload.isUploading = false
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

</script>

<template>
  <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body :close-on-click-modal="false" @close="closeDialog">
    <el-upload
        ref="uploadRef"
        :data="upload.data"
        :name="upload.name"
        :limit="1"
        :accept="upload.accept"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-exceed="handleExceed"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileFail"
        :auto-upload="false"
        drag
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 {{upload.accept}} 格式的文件。</span>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>